package com.ferry.taskflow.taskFlow.nontx;

import com.hualala.supplychain.support.taskFlow.base.Task;
import com.hualala.supplychain.support.taskFlow.base.TaskExecutor;
import com.hualala.supplychain.support.taskFlow.base.enumv.TaskState;
import com.hualala.supplychain.support.taskFlow.domain.TaskResult;
import lombok.extern.slf4j.Slf4j;

/**
 * Created by daiyong
 */
@Slf4j
public class NonTxTaskExecutor<RESULT> extends TaskExecutor<RESULT> {

	public NonTxTaskExecutor(Task<RESULT> task) {
		super(task);
	}

	//任务执行
	@Override
	public void execute() {

		if (getState() != TaskState.INIT.getCode()) {
			return;
		}

		try {

			//修改任务状态
			if (!this.state.compareAndSet(TaskState.INIT.getCode(), TaskState.DOING.getCode())) {
				log.warn("task is running. id:{}");
			}

			//执行任务
			RESULT result = task.execute();

			//执行完毕
			this.state.compareAndSet(TaskState.DOING.getCode(), TaskState.SUCCESS.getCode());

			//回调
			task.onSuccess(taskResult, result);

			taskResult = new TaskResult(true, true, null);

		} catch (Throwable throwable) {
			log.error("task run exception id:{}", throwable);

			//回调
			taskResult = new TaskResult(false, false, throwable);

			task.onFail(taskResult, throwable);

			//设置状态
			this.state.compareAndSet(TaskState.DOING.getCode(), TaskState.EXCEPTION.getCode());

			//抛出异常 主线程可以捕捉
			throw new RuntimeException(throwable);

		}
	}
}
